#include <iostream>
#include <sqlite3.h>
#include <string>
#include <vector>

class SqliteHelper
{
public:
    typedef int (*SqliteCallback)(void *, int, char **, char **);
    SqliteHelper(const std::string &dbfile) : _filename(dbfile), _handle(nullptr) {}
    bool open(int safe_leve = SQLITE_OPEN_FULLMUTEX)
    {
        int ret = sqlite3_open_v2(_filename.c_str(), &_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | safe_leve, nullptr);
        if (ret != SQLITE_OK)
        {
            std::cout << "创建/打开sqlite数据库失败:" << std::endl;
            std::cout << sqlite3_errmsg(_handle) << std::endl;
            return false;
        }
        return true;
    }
    bool exec(const std::string sql, SqliteCallback sc, void *arg)
    {
        int ret = sqlite3_exec(_handle, sql.c_str(), sc, arg, nullptr);
        if (ret != SQLITE_OK)
        {
            std::cout << sql << std::endl;
            std::cout << "执行语句失败: " << std::endl;
            std::cout << sqlite3_errmsg(_handle) << std::endl;
            return false;
        }
        return true;
    }
    bool close()
    {
        if (_handle)
        {
            int ret = sqlite3_close_v2(_handle);
            if (ret != SQLITE_OK)
            {
                std::cout << "关闭失败！" << std::endl;
                std::cout << sqlite3_errmsg(_handle) << std::endl;
                return false;
            }
            return true;
        }
        return true;
    }

private:
    std::string _filename;
    sqlite3 *_handle;
};
